﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Text;
using System.Threading;
using System.Management;

namespace Walson.IO.Ports
{
    /// <summary>
    /// 串口
    /// </summary>
    public class SerialPort : System.IO.Ports.SerialPort
    {
        /// <summary>
        /// 枚举win32 api
        /// </summary>
        private enum HardwareEnum
        {
            // 硬件
            Win32_Processor, // CPU 处理器
            Win32_PhysicalMemory, // 物理内存条
            Win32_Keyboard, // 键盘
            Win32_PointingDevice, // 点输入设备，包括鼠标。
            Win32_FloppyDrive, // 软盘驱动器
            Win32_DiskDrive, // 硬盘驱动器
            Win32_CDROMDrive, // 光盘驱动器
            Win32_BaseBoard, // 主板
            Win32_BIOS, // BIOS 芯片
            Win32_ParallelPort, // 并口
            Win32_SerialPort, // 串口
            Win32_SerialPortConfiguration, // 串口配置
            Win32_SoundDevice, // 多媒体设置，一般指声卡。
            Win32_SystemSlot, // 主板插槽 (ISA & PCI & AGP)
            Win32_USBController, // USB 控制器
            Win32_NetworkAdapter, // 网络适配器
            Win32_NetworkAdapterConfiguration, // 网络适配器设置
            Win32_Printer, // 打印机
            Win32_PrinterConfiguration, // 打印机设置
            Win32_PrintJob, // 打印机任务
            Win32_TCPIPPrinterPort, // 打印机端口
            Win32_POTSModem, // MODEM
            Win32_POTSModemToSerialPort, // MODEM 端口
            Win32_DesktopMonitor, // 显示器
            Win32_DisplayConfiguration, // 显卡
            Win32_DisplayControllerConfiguration, // 显卡设置
            Win32_VideoController, // 显卡细节。
            Win32_VideoSettings, // 显卡支持的显示模式。

            // 操作系统
            Win32_TimeZone, // 时区
            Win32_SystemDriver, // 驱动程序
            Win32_DiskPartition, // 磁盘分区
            Win32_LogicalDisk, // 逻辑磁盘
            Win32_LogicalDiskToPartition, // 逻辑磁盘所在分区及始末位置。
            Win32_LogicalMemoryConfiguration, // 逻辑内存配置
            Win32_PageFile, // 系统页文件信息
            Win32_PageFileSetting, // 页文件设置
            Win32_BootConfiguration, // 系统启动配置
            Win32_ComputerSystem, // 计算机信息简要
            Win32_OperatingSystem, // 操作系统信息
            Win32_StartupCommand, // 系统自动启动程序
            Win32_Service, // 系统安装的服务
            Win32_Group, // 系统管理组
            Win32_GroupUser, // 系统组帐号
            Win32_UserAccount, // 用户帐号
            Win32_Process, // 系统进程
            Win32_Thread, // 系统线程
            Win32_Share, // 共享
            Win32_NetworkClient, // 已安装的网络客户端
            Win32_NetworkProtocol, // 已安装的网络协议
            Win32_PnPEntity,//all device
        }

        /// <summary>
        /// 串口名称及其描述
        /// </summary>
        public class SerialPortDescription
        {
            /// <summary>
            /// 端口名
            /// </summary>
            public string PortName
            {
                get;
                set;
            }

            /// <summary>
            /// 驱动名
            /// </summary>
            public string DriverName
            {
                get;
                set;
            }

            /// <summary>
            /// 
            /// </summary>
            /// <returns></returns>
            public new string ToString()
            {
                return this.DriverName;
            }
        }

        bool _Exiting = false;
        bool _Running = false;

        List<string> _LastPortNames = new List<string>();
        List<SerialPortDescription> _Ports = new List<SerialPortDescription>();


        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            components = new System.ComponentModel.Container();
        }

        /// <summary>
        /// 获取端口列表
        /// </summary>
        /// <returns></returns>
        public SerialPortDescription[] GetPorts()
        {
            return _Ports.ToArray();
        }

        /// <summary>
        /// 端口列表变化（如 USB 转串口插入或拔出）
        /// </summary>
        /// <param name="sender">事件的发送方</param>
        /// <param name="e">参数</param>
        public delegate void PortListChangedEventHandler(object sender, EventArgs e);
        /// <summary>
        /// 端口列表变化事件
        /// </summary>
        public event PortListChangedEventHandler PortListChanged;
        protected void onPortListChanged()
        {
            if (this.PortListChanged != null)
            {
                this.PortListChanged(this, new EventArgs());
            }
        }

        /// <summary>
        /// 端口意外丢失（如 USB 转串口被拔出）
        /// </summary>
        /// <param name="sender">事件的发送方</param>
        /// <param name="e">参数</param>
        public delegate void PortLostEventHandler(object sender, EventArgs e);
        /// <summary>
        /// 端口意外丢失事件
        /// </summary>
        public event PortLostEventHandler PortLost;
        protected void onPortLost()
        {
            if (this.PortLost != null)
            {
                this.PortLost(this, new EventArgs());
            }
        }



        public delegate void DataReceivedHandler(object sender, EventArgs e);
        /// <summary>
        /// 表示数据接收事件的方法
        /// </summary>
        public new event DataReceivedHandler DataReceived;


        /// <summary>
        /// 表示串行端口资源
        /// </summary>
        public SerialPort()
        {
            InitializeComponent();
            CheckPortNames();
            BeginPortNameCheck();
            base.DataReceived += SerialPort_DataReceived;
        }


        /// <summary>
        /// 表示串行端口资源
        /// </summary>
        /// <param name="container"></param>
        public SerialPort(IContainer container)
        {
            container.Add(this);
            CheckPortNames();
            BeginPortNameCheck();
            InitializeComponent();

            base.DataReceived += SerialPort_DataReceived;
        }

        /// <summary>
        /// 打开一个新的串行端口连接
        /// </summary>
        public new void Open()
        {
            _Running = true;
            base.Open();
        }

        /// <summary>
        /// 关闭端口连接，将 System.IO.Ports.SerialPort.IsOpen 属性设置为 false，并释放内部 System.IO.Stream 对象
        /// </summary>
        public new void Close()
        {
            _Running = false;
            base.Close();
        }


        void SerialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            if (_Exiting || _Running == false)
                return;

            if (this.DataReceived != null)
            {
                this.DataReceived(this, e);
            }
        }

        private List<string> MulGetHardwareInfo(HardwareEnum hardType, string propKey)
        {

            List<string> strs = new List<string>();
            string name;
            try
            {
                using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from " + hardType))
                {
                    var hardInfos = searcher.Get();
                    foreach (var hardInfo in hardInfos)
                    {
                        name = (string)hardInfo.Properties[propKey].Value;
                        if (name.Contains("COM"))
                        {
                            strs.Add(hardInfo.Properties[propKey].Value.ToString());
                        }

                    }
                    searcher.Dispose();
                }
                return strs;
            }
            catch
            {
                return null;
            }
        }

        private void BeginPortNameCheck()
        {
            Thread thd = new Thread(new ThreadStart(thdCheckPortNames));
            thd.IsBackground = true;
            thd.Start();
        }

        private void CheckPortNames()
        {
            List<string> portNames = new List<string>();

            portNames.Clear();
            portNames.AddRange(System.IO.Ports.SerialPort.GetPortNames());

            if (_Running)
            {
                if (!portNames.Contains(this.PortName))
                {
                    this.Close();
                    onPortLost();
                }
            }

            bool portChanged = false;
            if (_LastPortNames.Count != portNames.Count)
            {
                portChanged = true;
            }
            else
            {
                foreach (string str in _LastPortNames)
                {
                    if (!portNames.Contains(str))
                    {
                        portChanged = true;
                        break;
                    }
                }
            }

            if (portChanged)
            {
                int[] numbers;
                string temp;

                _Ports.Clear();

                numbers = new int[portNames.Count];

                for (int i = 0; i < portNames.Count; i++)
                {
                    numbers[i] = Convert.ToInt32(portNames[i].Replace("COM", ""));
                }

                int temp2;
                for (int i = 0; i < numbers.Length - 1; i++)
                {
                    for (int j = i + 1; j < numbers.Length; j++)
                    {
                        if (numbers[i] > numbers[j])
                        {
                            temp2 = numbers[i];
                            numbers[i] = numbers[j];
                            numbers[j] = temp2;

                            temp = portNames[i];
                            portNames[i] = portNames[j];
                            portNames[j] = temp;

                        }
                    }
                }

                //通过WMI获取COM端口
                List<string> portDriverNameList = MulGetHardwareInfo(HardwareEnum.Win32_PnPEntity, "Name");
                System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"\bCOM\d{1,3}\b", System.Text.RegularExpressions.RegexOptions.Compiled);

                if (portDriverNameList != null)
                {
                    for (int i = 0; i < portDriverNameList.Count; i++)
                    {
                        string portNameInDriverName = r.Match(portDriverNameList[i]).Value;
                        SerialPortDescription port = new SerialPortDescription();
                        port.DriverName = portDriverNameList[i];
                        port.PortName = portNameInDriverName;
                        _Ports.Add(port);
                    }


                    //                         foreach (string portName in portNames)
                    //                         {
                    //                             foreach (string portDriverName in portDriverNameList)
                    //                             {
                    //                                 if (portDriverName.Contains("(" + portName + ")"))
                    //                                 {
                    //                                     SerialPortDescription port = new SerialPortDescription();
                    //                                     port.DriverName = portDriverName;
                    //                                     port.PortName = portName;
                    //                                     _Ports.Add(port);
                    //                                 }
                    //                             }
                    //                         }


                    _LastPortNames.Clear();
                    _LastPortNames.AddRange(portNames);

                    onPortListChanged();

                }
            }
        }

        private void thdCheckPortNames()
        {

            while (_Exiting == false)
            {
                CheckPortNames();

                Thread.Sleep(100);
            }
        }

        void Dispose()
        {
            _Exiting = true;
            base.DataReceived -= SerialPort_DataReceived;
            base.Dispose();
        }

        /// <summary> 
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源，为 true；否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            _Exiting = true;
            base.DataReceived -= SerialPort_DataReceived;

            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
